import pygame
from entitymanager import*
from UserInterface import*

class Editor(object):
   
    class editData(object):
        def __init__(self):
            self.clicked = 0
            self.originalPosition = (0,0)
            

    """For editing levels"""
    def __init__(self, game):
        UserInterface.game = game

        self.testUI = UserInterface.Container(game.screenWidth,game.screenHeight, 0, game.screen)
        self.inspector = Inspector(self.testUI)
        
        
        #Create texture entity spawner
        
        newUIContainer = UserInterface.Container(250,250, self.testUI)
        newUIContainer.addItem(UserInterface.BackgroundItem((255,255,255)))
        newUIContainer.items[0].action = UserInterface.MoveAction(newUIContainer.items[0])
        self.testUI.addContainer(newUIContainer)

        self.textureChooser = newUIContainer

        texStrings = []

        for tex in game.textures.keys():
            newTextItem = UserInterface.TextItem(tex)
            newTextItem.action = UserInterface.createEntityAction(newTextItem)
            texStrings.append(newTextItem)

        up = UserInterface.ListContainer(newUIContainer.rect.width, newUIContainer.rect.height, texStrings)
        down = UserInterface.Container(200,200)
        up.fill = True
        down.fill = True

        up.addItem(UserInterface.BackgroundItem((100,100,100)))
        down.addItem(UserInterface.BackgroundItem((0,0,0)))

        splitter = UserInterface.DividerContainer(newUIContainer, down, up, 230)

        newUIContainer.addContainer(splitter)
        

       

        self.manager = game.entitymanager
        self.mouserect = pygame.Rect(0,0,15,15)
        self.screenHeight = game.screenHeight
        self.screenWidth = game.screenWidth
        self.camera = game.camera
        self.inEditMode = 0

        self.game = game

        self.entitylock = 0
        self.entityLockOriginalPosition = (0,0)
        self.offsetPos = (0,0)
        self.entityWidth = 0
        self.entityHeight = 0
        self.stretchPlatform = 0
        self.moveEntity = 0

        self.mouseDownPos = (0,0)

        self.layer = 1 
        self.selection = {}

    def update(self, events, keysdown):
        self.waitInput(events)
        self.game.camera.update(4, self.game.entitymanager) ## This is horrible.
        if self.inEditMode:
         windowClicked = self.testUI.mouseCheck(pygame.mouse.get_pos())
         #If in edit mode run edity things
         if not windowClicked:
             self.editInput(events)
             self.updateEntityModify()
             self.clicked = True

         if(len(self.selection.keys()) > 0):
                self.inspector.changeTarget(self.selection.keys()[0])
         else:
                self.inspector.changeTarget(0)

    def updateEntityModify(self):
        self.mouserect.center = self.getPositionInRelationToCamera(pygame.mouse.get_pos()[0],pygame.mouse.get_pos()[1] )
        
        if(len(self.selection) > 0 ):
            
            for en in self.selection.keys():
                 if(not pygame.mouse.get_pressed()[0]):
                     self.selection[en].originalPosition = en.rect.center

                 if(pygame.mouse.get_pressed()[0]):
                     if(self.moveEntity):
                         #Move the selected entity
                         mouseCor = pygame.mouse.get_pos()
                         self.manager.quadtrees[int(en.layer)].removeEntity(en)
                         mouseOffsetX = (self.mouseDownPos[0] - pygame.mouse.get_pos()[0])
                         mouseOffsetY = (self.mouseDownPos[1] - pygame.mouse.get_pos()[1])
                         en.rect.center = (self.selection[en].originalPosition[0] - mouseOffsetX, self.selection[en].originalPosition[1] - mouseOffsetY)
                         self.manager.quadtrees[int(en.layer)].insertEntity(en)

                     if(self.stretchPlatform and isinstance(en, platform) and self.entitylock == en): #Kinda tough to grab a platform shrunk too far, but we'll leave it for now
                         #Stretches the grabbed target if it is a platform
                         self.manager.quadtrees[int(en.layer)].removeEntity(en)
                         width = (self.entityWidth - (self.offsetPos[0] - pygame.mouse.get_pos()[0]))
                         height = (self.entityHeight- (self.offsetPos[1] - pygame.mouse.get_pos()[1]))
                         if(width > 1):
                            en.rect.width = (self.entityWidth - (self.offsetPos[0] - pygame.mouse.get_pos()[0]))
                         if(height > 1):
                            en.rect.height = (self.entityHeight- (self.offsetPos[1] - pygame.mouse.get_pos()[1]))
                         self.manager.quadtrees[int(en.layer)].insertEntity(en)
        self.justselected = False
    
    def moveSelection(self, distance):
        pass

    def getPositionInRelationToCamera(self, x,y, parallax = [1,1]):
        return (x + self.camera.rect.x * parallax[0], y + self.camera.rect.y * parallax[1])

    def waitInput(self, events):
        for event in events:
            if event.type == pygame.KEYDOWN:
                if pygame.key.name(event.key) == 'e':
                    if(not self.inEditMode):
                        self.game.screen = pygame.display.set_mode((1200, 600))
                        self.game.camera.rect.width = 1200
                        self.game.camera.rect.height = 600
                        self.inspector.UIContainer.rect.x = (self.game.camera.rect.width - self.inspector.UIContainer.rect[3])
                        self.inspector.UIContainer.rect.y = (10)

                        self.textureChooser.rect.x = (self.game.camera.rect.width - self.inspector.UIContainer.rect[3])
                        self.textureChooser.rect.y = (self.game.camera.rect.height - self.inspector.UIContainer.rect[3] - 10)
                    else:
                        self.game.screen = pygame.display.set_mode((self.game.screenWidth, self.game.screenHeight))
                        self.game.camera.rect.width = self.game.screenWidth
                        self.game.camera.rect.height = self.game.screenHeight

                    self.inEditMode = not self.inEditMode
                    self.selection.clear()


    def editInput(self, events):
         for event in events:
             if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
                 self.mouserect.center = self.getPositionInRelationToCamera(event.pos[0],event.pos[1],self.manager.layerParallax[self.layer] )
                 
                 entitiesNearby = self.manager.getEntitiesNearby(self.mouserect, self.layer) #Probably should select closet of list
                 rectIndexHit = self.mouserect.collidelist(entitiesNearby)
                 
                 entityHit = []

                 self.mouseDownPos = event.pos

                 for entity in entitiesNearby:
                     if(entity.checkCollide(self.mouserect)):
                         entityHit.append(entity)
                         #break
                    
                 if len(entityHit) != 0:
                     
                     for en in entityHit[::-1]:
                         entityData = Editor.editData()
                         entityData.originalPosition =  en.rect.center
                         
                         self.offsetPos = event.pos
                         self.moveEntity = True
                         self.entityHitModify(en)
                         
                         if(not en in self.selection):
                            self.selection[en] = entityData
                            break
                         self.entitylock = en
                 else:
                     self.selection.clear()

             if event.type == pygame.MOUSEBUTTONUP and event.button == 1:
                self.entitylock = 0

             if event.type == pygame.KEYDOWN:
                  if pygame.key.name(event.key) == 'p':
                      newPlat = platform(self.manager)
                      newPlat.layer = self.layer
                      newPlat.rect.topleft = (self.getPositionInRelationToCamera(pygame.mouse.get_pos()[0], pygame.mouse.get_pos()[1]))
                      self.manager.addEntity(newPlat)

                  if pygame.key.name(event.key) == 't':
                        newTrig = trigger(self.manager)
                        newTrig.layer = self.layer
                        newTrig.rect.topleft = (self.getPositionInRelationToCamera(pygame.mouse.get_pos()[0], pygame.mouse.get_pos()[1]))
                        self.manager.addEntity(newTrig, True)

                  if pygame.key.name(event.key) == 'm':
                        newMove = moveable(self.manager)
                        newMove.layer = self.layer
                        newMove.rect.topleft = (self.getPositionInRelationToCamera(pygame.mouse.get_pos()[0], pygame.mouse.get_pos()[1]))
                        self.manager.addEntity(newMove, True)

                  if pygame.key.name(event.key) == 's':
                    self.game.level.save()

                  if pygame.key.name(event.key) == "delete" or pygame.key.name(event.key) == "backspace":
                      for en in self.selection:
                          self.manager.removeEntity(en, en.updates)
                      self.selection.clear()

                  if pygame.key.name(event.key) == '1':
                      self.layer = 1
                  if pygame.key.name(event.key) == '0':
                      self.layer = 0
                  if pygame.key.name(event.key) == '2':
                      self.layer = 2
                  if pygame.key.name(event.key) == '3':
                      self.layer = 3
              
    def entityHitModify(self, entity):
        if(isinstance(entity, platform)):
            if(pygame.Rect(entity.rect.bottomright[0] - 15, entity.rect.bottomright[1] - 15, 15, 15).collidepoint(self.mouserect.center)):
                self.stretchPlatform = True
                self.moveEntity = False
                self.entityWidth = entity.rect.width
                self.entityHeight = entity.rect.height
            else:
                self.stretchPlatform = False

    def draw(self, camera, screen):
        if(self.inEditMode):
            self.testUI.draw(screen)
            for en in self.selection.keys():
               self.drawForEntity(camera, screen, en)
    
    def drawForEntity(self, camera, screen, en):
        screenPos = en.getScreenPosition(camera, self.manager)
        offset = 10
        pygame.draw.rect(screen, (0,0,0),  (screenPos[0] - offset, screenPos[1] - offset, en.rect.width + offset * 2, en.rect.height + offset * 2), 2)

    def drawForPlatform(camera, screen):
        pass


